#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2020/3/30  14:49
# @Author: 余浪人
# @email: yulangren520@gmail.com
import math
import os
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from pathlib import Path
from apps.lib.cache_sys import sys_cache
from apps import get_sys_url
from apps.control import sys_bp
from flask import request, render_template, jsonify
from flask_login import login_required
from apps.models.content_model import TL_Content_Model, TL_Column_model

executor = ThreadPoolExecutor(10)


@sys_bp.route('/static_file_page', endpoint='static_file_page', methods=['GET', 'POST'])
@login_required
def static_file_page():
    if request.method == 'POST':
        if sys_cache().web_type != 2: return jsonify({'status': 4, 'msg': '当前为动态模式！'})
        type_data = request.form.get('type')
        sys_url = get_sys_url()
        html_path = os.path.join(sys_url, 'apps/static/html').replace('\\', '/')
        if not os.path.exists(html_path): os.mkdir(html_path)
        error = None
        if type_data == '1':
            page_html = ''
            try:
                html = Path(os.path.join(html_path, 'index.html').replace('\\', '/'))
                html.write_bytes(page_html.encode('utf-8'))
            except Exception as e:
                error = e
        elif type_data == '2':
            try:
                column_list = TL_Column_model.query.all()
                for column in column_list:
                    contList = TL_Content_Model.query.order_by(TL_Content_Model.is_list_stick.desc()).order_by(TL_Content_Model.id.desc()).filter(
                        TL_Content_Model.status == 1, TL_Content_Model.superior == column.id)
                    list_create(contList, column, html_path)
            except Exception as e:
                error = e
        elif type_data == '3':
            try:
                content_list = TL_Content_Model.query.order_by(TL_Content_Model.is_index_stick.desc()).order_by(TL_Content_Model.id.desc()).filter(
                    TL_Content_Model.status == 1, TL_Content_Model.update_time < datetime.now()).limit(5000).all()
                for content in content_list:
                    html_name = os.path.join(html_path, f'{content.uuid}.html')
                    if not os.path.exists(html_name):
                        page_html = ''
                        executor.submit(save_html, html_name, page_html)
            except Exception as e:
                error = e
        elif type_data == '4':
            try:
                html_list = os.listdir(html_path)
                for htm in html_list:
                    os.remove(os.path.join(html_path, htm))
            except Exception as e:
                error = e
        else:
            return jsonify({"未正确识别操作命令"})
        if error: return jsonify({'status': 4, 'msg': error})
        return jsonify({'status': 0})
    return render_template('system_template/static_file.html')


def save_html(html_name, page_html):
    with open(html_name, 'wb')as fp: fp.write(page_html.encode('utf-8'))


def list_create(dataList, column, html_path, p: int = 1):
    try:
        res = math.ceil(dataList.count() / 12)
    except:
        res = 1
    if res < p: p = 1
    paginate = dataList.paginate(p, 12)
    dataLis, pa = paginate.items, paginate
    page_path = os.path.join(html_path, f'{column.uuid}_{p}.html').replace('\\', '/')
    if not os.path.exists(page_path):
        html_page = ''
        save_html(page_path, html_page)
    if pa.has_next: list_create(dataList, column, html_path, pa.next_num)
